package com.qianchang.microfinance.view.base;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.PageBean;
import com.qianchang.microfinance.view.dialog.alert.DimengSingleButtonAlertDialog;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.DMLog;
import com.dm.library.utils.ToastUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;


public abstract class BaseRecyclerViewFragment<T> extends BaseFragment implements
        RecyclerRefreshLayout.SuperRefreshLayoutListener,
        BaseRecyclerAdapter.OnItemClickListener {
    private final String TAG = this.getClass().getSimpleName();
    protected BaseRecyclerAdapter<T> mAdapter;
    protected RecyclerView mRecyclerView;
    protected RecyclerRefreshLayout mRefreshLayout;
    protected boolean isRefreshing = true;
    protected PageBean<T> mBean;
    protected EmptyLayout mErrorLayout;
    protected int pageIndex = 1;
    protected RecyclerView rVrecommend;
    protected LinearLayout linearLayoutRecommend;


    @Override
    protected View onRootViewCreate(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return LayoutInflater.from(mContext).inflate(R.layout.fragment_base_recycler, container, false);
    }


    @Override
    protected void initView() {
        super.initView();
        mRecyclerView = (RecyclerView) mView.findViewById(R.id.recyclerView);
        mRefreshLayout = (RecyclerRefreshLayout) mView.findViewById(R.id.refreshLayout);
        mErrorLayout = (EmptyLayout) mView.findViewById(R.id.error_layout);

        linearLayoutRecommend = (LinearLayout) mView.findViewById(R.id.ll_bot_id);
        rVrecommend = (RecyclerView)mView.findViewById(R.id.recyclerView_recommend_id);

    }


    @SuppressWarnings("unchecked")
    @Override
    public void initData() {
        mBean = new PageBean<>();
        mAdapter = getRecyclerAdapter();
        mAdapter.setState(BaseRecyclerAdapter.STATE_HIDE, false);
        mRecyclerView.setLayoutManager(getLayoutManager());
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(this);
        mRefreshLayout.setSuperRefreshLayoutListener(this);

        boolean isNeedEmptyView = isNeedEmptyView();
        if (isNeedEmptyView) {
//            mErrorLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
            mBean = new PageBean<>();
            mBean.setList(new ArrayList<T>());
            mRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
//                    ((BaseActivity) mContext).show();
                    onRefreshing();
                    mRefreshLayout.setRefreshing(true);
                }
            });
        } else {
            mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
            mRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    mRefreshLayout.setRefreshing(true);
//                    ((BaseActivity) mContext).show();
                    onRefreshing();
                }
            });
        }

        mErrorLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onRefreshing();
            }
        });
    }

    public void setRefreshing(boolean refreshing) {
        isRefreshing = refreshing;
    }

    protected RequestCallBack<T> mCallBack = new RequestCallBack<T>() {

        @Override
        public Type getTokenType() {
            return getType();
        }

        @Override
        public void onSuccess(JsonResult<T> response) {
            onRequestFinish();
            try {
                if (response.getObject() == null) {
                    return;
                }
                if (!(response.getObject() instanceof PageBean)) {
                    throw new RuntimeException("the model is not instanceof PageBean");
                }
                PageBean<T> pageBean = (PageBean<T>) response.getObject();
                if (response.isReqDataSuccess() && pageBean.getList() != null) {
                    setListData(pageBean);
                    onRequestSuccess(response.getCode());
                } else {
                    mAdapter.setState(BaseRecyclerAdapter.STATE_NO_MORE, true);
                    ((BaseActivity) mContext).showAlertDialog(response.getDescription(), "我知道了", new DimengSingleButtonAlertDialog.OnDialogClickListener() {
                        @Override
                        public void agree() {

                        }
                    });
                }
            } catch (Exception e) {
                DMLog.i(TAG, e.getMessage());
                onFailure("服务器异常，请稍后再试");
            }
            setRefreshing(false);
            isShowEmptyView();
        }

        @Override
        public void onFailure(String msg) {
            onRequestFinish();
            onRequestError();
            setRefreshing(false);
            ToastUtil.getInstant().show(mContext, msg);
            isShowErrorView();
        }

        @Override
        public void onConnectFailure(String msg) {
        }

    };

    @Override
    public void onItemClick(int position, long itemId) {

    }

    @Override
    public void onRefreshing() {
        isRefreshing = true;
        mAdapter.setState(BaseRecyclerAdapter.STATE_HIDE, true);
        HttpParams params = new HttpParams();
        params.put("reqPageNum", 1);
        requestData(params);
    }

    @Override
    public void onLoadMore() {
        mAdapter.setState(isRefreshing ? BaseRecyclerAdapter.STATE_HIDE : BaseRecyclerAdapter.STATE_LOADING, true);
        HttpParams params = new HttpParams();
        params.put("reqPageNum", pageIndex);
        requestData(params);
    }

    protected abstract void requestData(HttpParams params);

    protected void onRequestSuccess(String code) {

    }

    protected void onRequestFinish() {
        onComplete();
    }

    protected void onRequestError() {
        if (mAdapter.getItems().size() == 0) {
            mAdapter.setState(BaseRecyclerAdapter.STATE_LOAD_ERROR, true);
        }
        if (!isRefreshing) {
            mAdapter.setState(BaseRecyclerAdapter.STATE_INVALID_NETWORK, true);
        }
    }

    protected void onComplete() {
//        if (null != mContext) {
//            ((BaseActivity) mContext).dismiss();
//        }
        mRefreshLayout.onComplete();
    }

    //    @SuppressWarnings("unchecked")
    protected void setListData(PageBean<T> pageBean) {
        boolean hasMoreData = pageBean.getList() != null && pageBean.isHasNextPage();
        Log.e(TAG, "setListData: " + isRefreshing);
        if (isRefreshing) {
            mBean.setList(pageBean.getList());
            mAdapter.clear();
            mAdapter.addAll(mBean.getList());
            isRefreshing = false;
        } else {
            mAdapter.addAll(pageBean.getList());
        }
        mRefreshLayout.setCanLoadMore(hasMoreData);
        pageIndex = isRefreshing ? 1 : pageBean.getPageIndex() + 1;
        if (!hasMoreData) {
            mAdapter.setState(BaseRecyclerAdapter.STATE_NO_MORE, true);
        }
    }

    public void isShowEmptyView() {
        if (mAdapter.getItems().size() > 0) {
            mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
            mRecyclerView.setVisibility(View.VISIBLE);
            mErrorLayout.setVisibility(View.GONE);
        } else {
            mRecyclerView.setVisibility(View.GONE);
            mErrorLayout.setVisibility(View.VISIBLE);
            mErrorLayout.setErrorType(isNeedEmptyView() ? EmptyLayout.NO_DATA : EmptyLayout.HIDE_LAYOUT);
        }
    }

    public void isShowErrorView() {
        if (mAdapter.getItems().size() > 0) {
            mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
            mRecyclerView.setVisibility(View.VISIBLE);
            mErrorLayout.setVisibility(View.GONE);
        } else {
            mRecyclerView.setVisibility(View.GONE);
            mErrorLayout.setVisibility(View.VISIBLE);
            mErrorLayout.setErrorType(isNeedEmptyView() ? EmptyLayout.NETWORK_ERROR : EmptyLayout.HIDE_LAYOUT);
        }
    }

    protected RecyclerView.LayoutManager getLayoutManager() {
        return new LinearLayoutManager(getActivity());
    }

    protected RecyclerView getRecyclerView() {
        return mRecyclerView;
    }

    protected abstract BaseRecyclerAdapter<T> getRecyclerAdapter();

    protected abstract Type getType();


    /**
     * 需要空的View
     *
     * @return isNeedEmptyView
     */
    protected boolean isNeedEmptyView() {
        return true;
    }


    /*****
     *
     *  设置是否显示底部的 我猜你是否喜欢 推荐产品功能
     */
    protected void showIsRecommend(boolean flag){
        if(flag){
            if(linearLayoutRecommend != null){
                linearLayoutRecommend.setVisibility(View.VISIBLE);
            }
        }else {
            if(linearLayoutRecommend != null){
                linearLayoutRecommend.setVisibility(View.GONE);
            }
        }
    }



}
